import { defineStore } from 'pinia'
import { ref } from 'vue'
import dayjs from 'dayjs'

// 签到记录类型
interface ICheckInRecord {
  id: string // 使用时间戳+随机数生成唯一ID
  userId: number
  name: string
  checkInTime: string // ISO格式时间字符串
  companyName?: string // 可选公司名称
}

export const useCheckInStore = defineStore(
  'checkIn',
  () => {
    // 签到记录列表
    const records = ref<ICheckInRecord[]>([])

    // 今日是否已签到
    const hasCheckedInToday = ref(false)

    // 最后签到记录
    const lastCheckIn = ref<ICheckInRecord | null>(null)

    // 初始化从本地存储加载数据
    const initFromStorage = () => {
      const storedRecords = uni.getStorageSync('checkInRecords')
      if (storedRecords) {
        records.value = JSON.parse(storedRecords)
        updateCheckInStatus()
      }
    }

    // 更新签到状态
    const updateCheckInStatus = () => {
      if (records.value.length > 0) {
        lastCheckIn.value = records.value[0]
        const lastDate = dayjs(lastCheckIn.value.checkInTime).format('YYYY-MM-DD')
        const today = dayjs().format('YYYY-MM-DD')
        hasCheckedInToday.value = lastDate === today
      } else {
        lastCheckIn.value = null
        hasCheckedInToday.value = false
      }
    }

    // 添加签到记录
    const addCheckIn = (record: Omit<ICheckInRecord, 'id'>) => {
      const newRecord: ICheckInRecord = {
        ...record,
        id: `${Date.now()}-${Math.random().toString(36).substr(2, 4)}`,
        checkInTime: dayjs().format('YYYY-MM-DD'), // 确保使用当前时间
      }

      records.value.unshift(newRecord) // 最新记录放在前面
      saveToStorage()
      updateCheckInStatus()
      return newRecord
    }

    // 删除签到记录
    const removeCheckIn = (id: string) => {
      records.value = records.value.filter((record) => record.id !== id)
      saveToStorage()
      updateCheckInStatus()
    }

    // 清除所有记录
    const clearAllRecords = () => {
      records.value = []
      lastCheckIn.value = null
      hasCheckedInToday.value = false
      uni.removeStorageSync('checkInRecords')
    }

    // 获取今日签到记录
    const getTodayRecords = () => {
      const today = dayjs().format('YYYY-MM-DD')
      return records.value.filter(
        (record) => dayjs(record.checkInTime).format('YYYY-MM-DD') === today,
      )
    }

    // 获取某天的签到记录
    const getRecordsByDate = (date: Date | string) => {
      const dateStr = dayjs(date).format('YYYY-MM-DD')
      return records.value.filter(
        (record) => dayjs(record.checkInTime).format('YYYY-MM-DD') === dateStr,
      )
    }

    // 保存到本地存储
    const saveToStorage = () => {
      uni.setStorageSync('checkInRecords', JSON.stringify(records.value))
    }

    // 初始化加载
    initFromStorage()

    return {
      records,
      hasCheckedInToday,
      lastCheckIn,
      addCheckIn,
      removeCheckIn,
      clearAllRecords,
      getTodayRecords,
      getRecordsByDate,
      updateCheckInStatus,
    }
  },
  {
    persist: {
      key: 'checkInStorage',
      paths: ['records'], // 只持久化records，其他状态由records计算得出
    },
  },
)
